<?php
declare(strict_types=1);


namespace App\Mall\Mapper;

use App\Mall\Model\MallGoods;
use App\Mall\Model\MallGoodsCategory;
use App\Mall\Model\MallGoodsShop;
use App\Mall\Model\MallGoodsTag;
use Hyperf\Database\Model\Builder;
use Mine\Abstracts\AbstractMapper;

/**
 * 商品列表Mapper类
 */
class MallGoodsMapper extends AbstractMapper
{
    /**
     * @var MallGoods
     */
    public $model;

    public function assignModel()
    {
        $this->model = MallGoods::class;
    }

    /**
     * 搜索处理器
     * @param Builder $query
     * @param array $params
     * @return Builder
     */
    public function handleSearch(Builder $query, array $params): Builder
    {
        // 主键
        if (isset($params['id']) && filled($params['id'])) {
            $query->where('id', '=', $params['id']);
        }

        // 编号
        if (isset($params['no']) && filled($params['no'])) {
            $query->where('no', '=', $params['no']);
        }


        if (isset($params['shop_id']) && filled($params['shop_id'])) {
            $query->where('shop_id', '=', $params['shop_id']);
        } else {
            $this->getIn($query);
        }

        // 上架
        if (isset($params['online']) && filled($params['online'])) {
            $query->where('online', '=', $params['online']);
        }

        $query->selectRaw('mall_goods.*');
        return $query->with(['category', 'tag', 'shop']);
    }

    public function handlePageItems(array $items, array $params): array
    {
        foreach ($items as $item) {
            $cates = $item->category->toArray();
            $tags = $item->tag->toArray();
            $shops = $item->shop->toArray();
            $item->cate_ids = array_column($cates, 'category_id');
            $item->tag_ids = array_column($tags, 'tag_id');
            $item->shop_ids = array_column($shops, 'shop_id');
            $item->setHidden(['category']);
            $item->setHidden(['tag']);
            $item->setHidden(['shop']);
        }
        return $items;
    }

    public function save(array $data): mixed
    {
        $data['no'] = redis()->hIncrBy('gene', 'did', 1);
        $data['shop_id'] = redis()->hGet('admin:' . user()->getId(), 'main_shop_id') ?: 0;
        $id = parent::save($data);
        if ($id) $this->extracted($data, $id);
        return $id;
    }

    public function update(mixed $id, array $data): bool
    {
        $s = parent::update($id, $data);
        if ($s) $this->extracted($data, $id);
        return $s;
    }

    public function extracted(array $data, mixed $id): void
    {
        MallGoodsCategory::query()->where(['goods_id' => $id])->delete();
        MallGoodsTag::query()->where(['goods_id' => $id])->delete();
        MallGoodsShop::query()->where(['goods_id' => $id])->delete();
        $in = $in2 = $in3 = [];
        foreach ($data['cate_ids'] ?? [] as $cate_id) {
            $in[] = [
                'category_id' => $cate_id,
                'goods_id' => $id,
            ];
        }
        foreach ($data['tag_ids'] ?? [] as $tag_id) {
            $in2[] = [
                'tag_id' => $tag_id,
                'goods_id' => $id,
            ];
        }
        foreach ($data['shop_ids'] ?? [] as $shop_id) {
            $in3[] = [
                'shop_id' => $shop_id,
                'goods_id' => $id,
            ];
        }
        if ($in) MallGoodsCategory::query()->insert($in);
        if ($in2) MallGoodsTag::query()->insert($in2);
        if ($in3) MallGoodsShop::query()->insert($in3);
    }

    public function select(array $param)
    {
        $query = $this->model->query()->select(['id', 'name']);
        $this->getIn($query);
        return $query->get()->map(function ($item) {
            $item->name = fastapp_lang_text($item->name);
            return $item;
        });
    }

    public function getIn($query): void
    {
        $admin_id = user()->getId();
        if ($admin_id != env('SUPER_ADMIN')) {
            $res = redis()->hGetAll('admin:' . $admin_id);
            if (empty($res)) return;
            $tb = 'mall_goods_shop';
            $query->where(['mall_goods.shop_id' => $res['main_shop_id']])
                ->leftJoin($tb, 'mall_goods.id', '=', $tb . '.goods_id')
                ->whereIn($tb . '.shop_id', explode(',', $res['shop_id']));
        }
    }
}